import {
  DateFormat
} from './utils';
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import {
  showMsg
} from '../../../../utils/config';
import {
  dataHandle,
  dataHandle1,
} from "../../../../utils/time"
let talkBack = require('../behaviors/live/talk-back.js') //对讲

//index.js
//获取应用实例
const app = getApp();
const recorderManager = wx.getRecorderManager();

const options = {
  duration: 60000, //指定录音的时长，单位 ms，最大为10分钟（600000），默认为1分钟（60000）
  sampleRate: 16000, //采样率
  numberOfChannels: 1, //录音通道数
  format: 'mp3', //音频格式，有效值 aac/mp3
}

var livePlayerContext;

import {
  OPEN_DOMAIN,
  PTZ_START,
  PTZ_STOP
} from './config';

Page({
  behaviors: [talkBack],
  data: {
    scene: 1001,
    accessToken: '',
    deviceSerial: '',
    channelNo: '1',
    list: [{
        id: 'talk',
        name: '对讲',
        status: -1,
        imageUrl: './image/talk.svg',
        abnormalImage: './image/talk-disabled.svg'
      },
      {
        id: 'ptz',
        name: '云台控制',
        status: -1,
        imageUrl: './image/yuntai.svg',
        abnormalImage: './image/yuntai-disabled.svg'
      },
      {
        id: 'voice',
        name: '语音播报',
        status: -1,
        imageUrl: './image/record.svg',
        abnormalImage: './image/record-disable.svg'
      },
      {
        id: 'playback',
        name: '回放',
        status: 0,
        imageUrl: './image/backward.svg',
        abnormalImage: './image/backward.svg'
      },
      {
        id: 'capture',
        name: '截屏',
        status: -1,
        imageUrl: './image/picture-shoot.svg',
        abnormalImage: './image/pictureshoot-disabled.svg'
      },
      {
        id: 'mirror',
        name: '镜像翻转',
        status: -1,
        imageUrl: './image/jingxiang.svg',
        abnormalImage: './image/jingxiang-disabled.svg'
      },
      {
        id: 'cover',
        name: '镜头遮蔽',
        status: -1,
        imageUrl: './image/yinsi.svg',
        abnormalImage: './image/yinsi-disabled.svg'
      },
    ],
    videoSrc: "", //标清
    videoHDSrc: "", //高清
    panelStatus: 0, //0: 展示面板 1：进入云台 2-进入语音播报 3-进入镜像翻转 4-进入镜头遮蔽 5-对讲,
    ptzDisabled: true,
    voiceDiasbled: true,
    mirrorDisabled: true,
    mirrorInterval: false,
    coverDisabled: true,
    coverInterval: false,
    showVideoControls: true,
    autoHideTimer: undefined,
    videoLoadingStatus: 0,
    playVideo: false,
    videoNetWorkError: false,
    objectFit: 'contain',
    openSound: true,
    isHD: false,
    showHDSelect: false,
    fullScreen: false,
    ptzStatus: 0, //0-初始化 1-top noraml 2-downnoraml 3-left normal 4-right normal  5-top noraml 6-down limit 7-left limit 8-right limit
    ptzLoading: false,
    ptzLimit: '',
    deviceOffline: false,
    deviceOfflineTime: new Date(),
    deviceName: '',
    currentPtzImg: './images/yuntai/normal.png',
    // 语音播报
    activeDefaultVoiceName: '',
    activeCustomVoiceName: '',
    defaultVoiceList: [], // 默认语音列表
    defaultVoiceTotal: 0, // 默认语音总数
    defaultVoicePage: 0, // 默认语言当前页
    defaultVoiceListLoading: false,
    defaultVoiceNoMore: false,
    customVoiceList: [], // 默认语音列表
    customVoiceTotal: 0, // 默认语音总数
    customVoicePage: 0, // 默认语言当前页
    customVoiceListLoading: false,
    customVoiceListNoMore: false,
    recoderTime: 60,
    recoderTimer: undefined,
    sendingOnceVoice: false,
    dialogTitle: '',
    dialogContent: '',
    buttons: [{
      text: '知道了'
    }],
    dialogShow: false,
    pathParam: '',

    // 对讲过程
    token1: '', // 用于邀请设备入会
    token2: '', // 用于强制设备退会
    websocketUrl: '',
    clientId: 993089712, // 注意：通讯过程中真实的clientId，此处仅供调试，无需赋值
    roomId: 0, // 注意：需要加入的房间号，需外部提供
    joinPassword: '', // 注意：加入房间的密码，需外部提供
    vtmHttpsAddress: '',
    vtmIp: 'test11.ys7.com', // 此处仅供调试，无需赋值
    vtmPort: 8554, // 此处仅供调试，无需赋值
    rtmpAddress: '', // push/play地址
    rtmpPort: '', // 推流拉流端口地址
    lockReconnect: false, // websocket重连
    limit: 0,
    timer: null,
    pushVideo: true, // 推流
    pushVideoContext: null,
    pushUrl: '', // 推流地址
    livePlayerContext: [

    ], // 播放节点
    showVideoControls: false,
    videoNetWorkError: false,
    playSrc: '', // 播放地址

    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    iteminfo: {},
    nottext: "暂无录像",
    // tab切换
    currentTab: 0,
    isShowCalendar: false,
    maxDate: new Date(dataHandle()).getTime(),
    minDate: new Date(2022, 0, 1).getTime(),
    isDay: true,
    // minDate: 0, // 初始化为0，稍后将计算当前日期前30天的日期  
    // maxDate: 0, // 初始化为0，稍后将计算当前日期  
    defaultDate: new Date(dataHandle()).getTime(),
    dateTime: '', // 当前选择日期

    dateLine: [], // 时间片段
    recType: 2, // 1-云存储，2-本地录像
    date: '', // 当前选择日期
    switchText: '本地',
    idinfo: -1, //-1直播 -2时间轴 其他卡片
    playFlag: false, //回放 true  直播 false
    durationSeconds: null,
    cardType: 2, //1时间轴 2卡片
    playCode: 0, // 当前播放错误码，
    startTimest: "",
    endTimeet: "",
    Arr: [],
    IsNextPage: false,
    deviceInfo: {},
    loadingText: "视频安全传输中",
    PageActive: true,

    timer: null
  },
  onLaunch() {},
  onShow() {
    // console.log("show");
    // var launchOptions = wx.getEnterOptionsSync();
    // const pathParam = launchOptions.query.scene;
    // console.log('pathParam:', pathParam);
    // this.setData({
    //   pathParam: pathParam
    // });
    // if (pathParam) {
    //   this.getWxaInfo();
    // }
    // Do something when show.
    // this.checkNetWork();
  },
  onHide() {
    // Do something when hide.
    console.log("hide")
    this.setData({
      panelStatus: 0,
      pathParam: ''
    });
    console.log(this.data.pathParam);
  },
  onError(msg) {
    console.log(msg)
  },
  // 获取当天日期
  getTodayDate() {
    const that = this;
    let type = null;
    var time = new Date();
    var h = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    let date = (h > 9 ? h : '0' + h) + '-' + (m > 9 ? m : '0' + m) + '-' + (d > 9 ? d : '0' + d);
    // let date =  (m > 9 ? m : '0' + m) + '-' + (d > 9 ? d : '0' + d);
    this.setData({
      date: date,
      dateTime: dataHandle1(),
    });
  },
  // 获取token
  gettoken() {
    wx.request({
      url: `https://open.ys7.com/api/lapp/token/get`,
      method: 'POST',
      data: {
        appKey: 'd6a1a4287b9a4d78adebaa7bbc8c7125',
        appSecret: '6b9102e6b4ef80beb7067be13d08bd2c',
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: async (res) => {
        console.log(res);
        this.setData({
          accessToken: res.data.data.accessToken
        })
        this.getPlayUrl(); //直播
        this.getDevice() //获取单个设备信息
        // await this.getDeviceInfo();//lc
        // await this.getDeviceCoverInfo();//lc
      }
    });
  },
  onLoad(e) {
    this.gettoken()
    this.getTodayDate()
    this.calculateDateRange(); // 计算日期范围  
    console.log(JSON.parse(e.info));
    let item = JSON.parse(e.info)
    console.log(item);
    // 截取 : 后面的数字  
    // let index = item.imei.indexOf(":");  
    // if (index !== -1) {  
    //   this.setData({  
    //     imeiAfterColon: item.imei.substring(index + 1)  
    //   });  
    // }  
    // var launchOptions = wx.getLaunchOptionsSync();
    // const { accessToken, deviceSerial,channelNo,scene } = query;
    // console.log("分享获得的参数",accessToken, deviceSerial,channelNo,scene)
    this.setData({
      scene: 1001,
      // accessToken: item.accessToken,
      deviceSerial: item.sn,
      iteminfo: item,
      channelNo: 1,
      panelStatus: 0, // todo -0
    });

    this.setData({
      showOneButtonDialog: true
    });
    // 录音模块
    // recorderManager.onStart(() => {
    //   console.log('recorder start');
    // })
    // recorderManager.onPause(() => {
    //   console.log('recorder pause');
    //   this.speakEnd();
    // })
    // recorderManager.onInterruptionBegin(this.speakEnd);

    // recorderManager.onStop((res) => {
    //   console.log('recorder stop', res)
    //   const {
    //     recoderTime
    //   } = this.data;
    //   const {
    //     tempFilePath
    //   } = res;
    //   if (recoderTime >= 59) {
    //     this.setData({
    //       recoderTime: 60,
    //     })
    //     clearTimeout(this.data.recoderTimer);
    //     return false;
    //   }
    //   this.setData({
    //     sendingOnceVoice: true,
    //   })
    //   wx.uploadFile({
    //     url: `${OPEN_DOMAIN}/api/lapp/voice/sendonce`, //仅为示例，非真实的接口地址
    //     filePath: tempFilePath, //tempFilePaths[0],
    //     name: 'voiceFile',
    //     formData: {
    //       accessToken: accessToken,
    //       deviceSerial: deviceSerial,
    //       channelNo: channelNo,
    //     },
    //     header: {
    //       'content-type': 'amultipart/form-data' // 默认值
    //     },
    //     success: (res) => {
    //       let data = res.data;
    //       if (!data.code) {
    //         data = JSON.parse(data);
    //       }
    //       console.log(data);
    //       if (data.code == 200) {
    //         console.log("发送成功");
    //       } else if (data.code == '111012') { // 设备正忙
    //         wx.showToast({
    //           title: '语音下发失败',
    //           icon: 'none',
    //         })
    //       } else if (data.code == '20007') { // 设备正忙
    //         wx.showToast({
    //           title: '设备不在线',
    //           icon: 'none',
    //         })
    //       } else if (data.code == '20008') { // 设备正忙
    //         wx.showToast({
    //           title: '设备响应超时',
    //           icon: 'none',
    //         })
    //       } else {
    //         wx.showToast({
    //           title: data.msg,
    //           icon: 'none',
    //         })
    //       }
    //       this.setData({
    //         recoderTime: 60,
    //       })
    //       //do something
    //     },
    //     fail: (res) => {
    //       wx.showToast({
    //         title: '网络异常',
    //         icon: 'none'
    //       })
    //     },
    //     complete: () => {
    //       this.setData({
    //         sendingOnceVoice: false,
    //       })
    //     }
    //   })
    // })
    // recorderManager.onFrameRecorded((res) => {
    //   const {
    //     frameBuffer
    //   } = res
    //   console.log('frameBuffer.byteLength', frameBuffer.byteLength)
    // });
    //视频
    livePlayerContext = wx.createLivePlayerContext('livePlayer');
    console.log("livePlayerContext", livePlayerContext);
  },
  // 计算日期范围  
  calculateDateRange: function () {
    const today = new Date();
    // 计算30天前的日期  
    const minDate = new Date(today);
    minDate.setDate(minDate.getDate() - 30);
    // maxDate设置为今天的日期  
    const maxDate = new Date(today);
    // 更新data中的值  
    this.setData({
      minDate: minDate.getTime(),
      maxDate: maxDate.getTime(),
    });
  },

  initPannel(moduleId) {

  },
  // 获取单个设备信息
  getDevice() {
    const {
      accessToken,
      deviceSerial,
    } = this.data;
    var _this = this;
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/device/info`,
      method: 'POST',
      data: {
        accessToken: accessToken,
        deviceSerial: deviceSerial,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res, '获取单个设备信息');
        _this.setData({
          deviceInfo: res.data.data
        })
      }
    })
  },
  getPlayUrl() {
    const {
      accessToken,
      deviceSerial,
      channelNo
    } = this.data;
    var _this = this;
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/v2/live/address/get`,
      method: 'POST',
      data: {
        accessToken: accessToken,
        deviceSerial: deviceSerial,
        channelNo: channelNo,
        expireTime: 86400,
        quality: 2,
        protocol: 3,
        supportH265: 1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: async (res) => {
        console.log(res.data, '标清视频流');
        const {
          list
        } = this.data;
        if (res.data.code == 200 && res.data.data && res.data.data.url) {
          var result = res.data;
          if (result.code == 200) {
            _this.setData({
              videoSrc: result.data.url,
            })
          } else {
            list[0].status = -1;
            list[1].status = -1;
            list[2].status = -1;
            list[4].status = -1;
            list[5].status = -1;
            list[6].status = -1;
            _this.setData({
              list: list,
              dialogContent: result.msg,
              showVideoControls: false,
            })
          }
          _this.setData({
            playFlag: false,
          })
          // await this.onready()//加载中
          await this.onVideoTap() //点击视频
          this.data.timer && clearTimeout(this.data.timer)
          this.data.timer = setTimeout(() => {
            this.handlePlay(); //开始播放
          }, 500)
          this.setData({
            timer: this.data.timer
          })
        } else if (res.data.code == "20001" || res.data.code == "20002" || res.data.code == '20018' || res.data.code == '10001') { // 设备不存在 / 不属于用户
          // this.setData({
          //   dialogTitle: '获取播放地址失败',
          //   dialogContent: '该用户不拥有该设备',
          //   dialogShow: true,
          // })
          Dialog.alert({
            message: '该用户不拥有该设备',
          }).then(() => {
            wx.navigateBack()
          });
        } else {
          Dialog.alert({
            message: res.data.msg,
          }).then(() => {
            wx.navigateBack()
          });
          console.log("获取播放地址失败")
          return;
          // _this.openPlayUrl();
        }
      }
    });
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/v2/live/address/get`,
      method: 'POST',
      data: {
        accessToken: accessToken,
        deviceSerial: deviceSerial,
        channelNo: channelNo,
        expireTime: 86400,
        quality: 1,
        protocol: 3,
        supportH265: 1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res.data, '高清视频流');
        const {
          list
        } = this.data;
        if (res.data.code == 200 && res.data.data && res.data.data.url) {
          var result = res.data;
          if (result.code == 200) {
            _this.setData({
              videoHDSrc: result.data.url,
            })
          } else {
            llist[0].status = -1;
            list[1].status = -1;
            list[2].status = -1;
            list[4].status = -1;
            list[5].status = -1;
            list[6].status = -1;
            _this.setData({
              list: list,
              dialogContent: result.msg,
              showVideoControls: false,
            })
          }
        } else {
          console.log("获取高清播放地址失败")
          // _this.openPlayUrl();
        }
      }
    })
  },
  /*
   * 获取设备基本信息
   */
  getDeviceCoverInfo() {
    const {
      accessToken,
      deviceSerial,
      channelNo
    } = this.data;
    console.log(accessToken, deviceSerial, channelNo);
    var _this = this;
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/device/scene/switch/status`,
      method: 'POST',
      data: {
        accessToken,
        deviceSerial,
        channelNo,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res.data);
        if (res.data.code == 200 && res.data.data) {
          const result = res.data.data;
          let list = this.data.list;
          if (result.enable == 1) { // 当前镜头遮蔽中

            list[0].status = -1;
            list[1].status = -1;
            list[2].status = -1;
            list[4].status = -1;
            list[5].status = -1;
            list[6].status = 1;
            this.setData({
              videoNetWorkError: false,
              showVideoControls: false,
              panelStatus: 4,
              videoLoadingStatus: 100,
              list: list,
            })
            console.log("panelStatus", this.data.panelStatus)
          }
        }
      },
      error: (err) => {
        console.log(err);
      },
    })
  },

  /*
   * 获取设备基本信息
   */
  getDeviceInfo() {
    const {
      accessToken,
      deviceSerial,
      channelNo,
      showVideoControls,
      videoNetWorkError,
      videoLoadingStatus
    } = this.data;
    var _this = this;
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/device/info`,
      method: 'POST',
      data: {
        accessToken,
        deviceSerial,
        channelNo,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res.data);
        if (res.data.code == 200 && res.data.data) {
          let list = this.data.list;
          var result = res.data.data;
          _this.setData({
            deviceName: result.deviceName,
            deviceOffline: result.status !== 1,
            videoNetWorkError: result.status !== 1 ? false : videoNetWorkError,
            showVideoControls: result.status !== 1 ? false : showVideoControls,
            deviceOfflineTime: DateFormat(new Date(result.updateTime), 'yyyy-MM-dd hh:mm:ss'),
            deviceIsEncrypt: result.isEncrypt,
            videoLoadingStatus: (result.isEncrypt === 1 || result.status !== 1) ? 100 : videoLoadingStatus,
          });
          // 配置标题
          if (result.deviceName) {
            wx.setNavigationBarTitle({
              title: result.deviceName,
            })
          }
          if (result.status != 1) { // 设备不在线
            list[0].status = -1;
            list[1].status = -1;
            list[2].status = -1;
            list[4].status = -1;
            list[5].status = -1;
            list[6].status = -1;
            _this.setData({
              list: list,
              showVideoControls: false
            })
          } else if (result.isEncrypt == 1) { // 设备被加密
            list[0].status = -1;
            list[1].status = -1;
            list[2].status = -1;
            list[4].status = -1;
            list[5].status = -1;
            list[6].status = -1;
            _this.setData({
              list: list,
              // dialogTitle: '设备被加密',
              // dialogContent: '设备已被加密，无法继续查看，请前往萤石云app解密。',
              // dialogShow: true,
              showVideoControls: false,
            })
            Dialog.alert({
              message: '设备已被加密，无法继续查看，请前往萤石云app解密。',
            }).then(() => {});
          } else {
            // 获取设备能力
            // _this.getDeviceCapacity();
            _this.getDeviceCoverInfo();
          }
        } else if (res.data.code == "20001" || res.data.code == "20002" || res.data.code == '20018') { // 设备不存在 / 不属于用户
          // this.setData({
          //   dialogTitle: '获取播放地址失败',
          //   dialogContent: '该用户不拥有该设备',
          //   dialogShow: true,
          // })
          Dialog.alert({
            message: '该用户不拥有该设备',
          }).then(() => {});
        } else if (res.data.code == 10029) {
          wx.showToast({
            title: '个人版接口调用超限，请升级企业版',
            icon: 'none',
          })
        } else if (res.data.code == 10002) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
          setTimeout(() => {
            this.pageBack();
          }, 2000)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  /*
   * 获取设备能力集
   */
  getDeviceCapacity() {
    const {
      accessToken,
      deviceSerial,
      channelNo,
      playVideo
    } = this.data;
    var _this = this;
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/device/capacity`,
      method: 'POST',
      data: {
        accessToken,
        deviceSerial,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res.data, '能力集');
        if (res.data.code == 200 && res.data.data) {
          var result = res.data.data;
          let list = this.data.list;
          list[0].status = result.support_talk != (1 || 4) ? -1 : 0;
          list[1].status = result.support_ptz == 0 ? -1 : 0;
          list[2].status = result.support_talk != 1 ? -1 : 0;
          list[5].status = result.ptz_top_bottom_mirror == 0 ? -1 : 0;
          list[6].status = result.support_privacy == 0 ? -1 : 0;
          if (!playVideo) { // 非视频播放成功状态下
            list[0].status = -1;
            list[1].status = -1;
            list[4].status = -1;
            list[5].status = -1;
          }
          _this.setData({
            list: list,
          })
        } else if (res.data.code == "20002" || res.data.code == '20018') { // 设备不存在 / 不属于用户
          // this.setData({
          //   dialogTitle: '设备被删除',
          //   dialogContent: '设备已从账号下删除，无法继续查看',
          //   dialogShow: true,
          // })
          Dialog.alert({
            message: '设备已从账号下删除，无法继续查看',
          }).then(() => {});
        }
      }
    })
  },
  fullScreen() {
    var _this = this;
    livePlayerContext.requestFullScreen({
      direction: 90,
      success: function () {
        _this.setData({
          fullScreen: true,
        })
      }
    });
    console.log("开启全屏");
  },
  unfullScreen() {
    var _this = this;
    livePlayerContext.exitFullScreen({
      success: function () {
        _this.setData({
          fullScreen: false,
        })
      }
    });
    console.log("退出全屏");
  },
  ToggleObjectFit() {
    var objectFit = this.data.objectFit;
    this.setData({
      objectFit: objectFit === 'contain' ? 'fillCrop' : 'contain',
    })
  },
  fullscreenChange(event) {
    console.log("监听到全屏变化", event)
  },
  getDefaultVoice: function () {
    const {
      accessToken
    } = this.data;
    var _this = this;
    console.info("默认语音： 第" + _this.data.defaultVoicePage + "页");
    var _this = this;
    _this.setData({
      defaultVoiceListLoading: true,
    })
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/voice/query`, //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        "accessToken": accessToken,
        "default": "true",
        "pageStart": _this.data.defaultVoicePage,
        "pageSize": 5,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        console.log(res.data);
        var defaultVoiceList = _this.data.defaultVoiceList;
        defaultVoiceList = defaultVoiceList.concat(res.data.data);
        if (res.data.data && res.data.data.length > 0) {
          _this.setData({
            defaultVoiceList: defaultVoiceList,
            defaultVoicePage: _this.data.defaultVoicePage + 1,
          });
        } else {
          _this.setData({
            defaultVoiceNoMore: true,
          });
        }
        _this.setData({
          defaultVoiceListLoading: false,
        })
      },
      error(error) {
        console.log(error);
        _this.setData({
          defaultVoiceListLoading: false,
        })
      }
    })
  },
  getCustomVoice: function () {
    const {
      accessToken
    } = this.data;
    var _this = this;
    console.info("用户自定义语音： 第" + _this.data.defaultVoicePage + "页");
    var _this = this;
    _this.setData({
      customVoiceListLoading: true,
    })
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/voice/query`, //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        "accessToken": accessToken,
        default: false,
        "pageStart": _this.data.defaultVoicePage,
        "pageSize": 5,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        console.log(res.data);
        var customVoiceList = _this.data.customVoiceList;
        customVoiceList = customVoiceList.concat(res.data.data);
        if (res.data.data && res.data.data.length > 0) {
          _this.setData({
            customVoiceList: customVoiceList,
            customVoicePage: _this.data.customVoicePage + 1,
          });
        } else {
          _this.setData({
            customVoiceNoMore: true,
          });
        }
        _this.setData({
          customVoiceListLoading: false,
        })
      },
      error(error) {
        console.log(error);
        _this.setData({
          customVoiceListLoading: false,
        })
      }
    })
  },
  // 滚动至低端事件
  defaultScrollLower: function () {
    var _this = this;
    console.info("defaultScrollLower 第" + _this.data.defaultVoicePage + "页");
    this.getDefaultVoice();
  },
  // 加载中
  onready() {
    this.setData({
      videoLoadingStatus: 10,
      videoNetWorkError: false
    })
  },
  // 滚动至低端事件
  customScrollLower: function () {
    var _this = this;
    console.info("customScrollLower 第" + _this.data.defaultVoicePage + "页");
    this.getCustomVoice();
  },
  // 重试逻辑
  onRetry() {
    if (this.data.idinfo == -1) {
      this.setData({
        showVideoControls: false,
        videoNetWorkError: true,
        videoLoadingStatus: 100,
        loadingText: "正在重连中",
      })
      // 直播
      this.getPlayUrl()
    } else {
      // 回放
      this.handlePlay()
    }
  },
  // 播放
  handlePlay(callback) {
    console.log('播放地址：', this.data.isHD, this.data.videoHDSrc, this.data.videoSrc)
    let {
      list
    } = this.data;
    this.checkNetWork()
    this.setData({
      videoLoadingStatus: 10,
      videoNetWorkError: false,
      // loadingText: "视频安全传输中",
    })
    livePlayerContext.play({
      success: () => {
        this.setData({
          showVideoControls: true,
          videoNetWorkError: false,
        });
        if (callback && typeof callback === "function") {
          callback();
        }
      },
      fail: (error) => {
        this.checkNetWork();
        wx.showToast({
          title: '网络异常',
          icon: 'none',
        })
        console.log("开始播放失败");
        list[4].status = 0;
        this.setData({
          videoNetWorkError: true,
          showVideoControls: false,
          videoLoadingStatus: 100,
          list: [...list]
        })
      }
    })
  },
  // 停止
  handleStop3(callback) {
    console.log("stop");
    let {
      list
    } = this.data;
    livePlayerContext.stop({
      success: () => {
        console.log("停止播放成功")
      },
      fail: (error) => {
        console.log("停止播放失败")
      }
    })
  },
  // 停止
  handleStop(callback) {
    console.log("stop");
    let {
      list
    } = this.data;
    livePlayerContext.stop({
      success: () => {
        list[1].status = -1;
        this.setData({
          playVideo: false,
          videoLoadingStatus: 0,
          list: list,
          panelStatus: 0,
        })
        if (callback && typeof callback === "function") {
          callback();
        }
      },
      fail: (error) => {
        console.log("停止播放失败")
      }
    })
  },
  autoHideControl() {
    console.log("showHdSelect", this.data.showHDSelect);
    const _this = this;
    clearTimeout(this.data.autoHideTimer);
    this.data.autoHideTimer = setTimeout(() => {
      const {
        showHDSelect
      } = _this.data;
      if (!showHDSelect) {
        this.setData({
          showVideoControls: false,
        })
      }
    }, 5000);
  },
  handleSound(e) {
    var openSound = this.data.openSound;
    this.setData({
      openSound: !openSound,
    })
  },
  handleHD(e) {
    var showHDSelect = this.data.showHDSelect;
    console.log("handleHD", showHDSelect)
    this.setData({
      showHDSelect: !showHDSelect,
    });
  },
  changeVideoHD(e) {
    var _this = this;
    this.setData({
      showHDSelect: false,
      isHD: true
    });
    this.handleStop(_this.handlePlay);
  },
  changeVideoNormal(e) {
    this.setData({
      showHDSelect: false,
      isHD: false
    })
    this.handleStop(this.handlePlay);
  },
  statechange(e) {
    console.log('live-player code:', e.detail.code, e.detail);
    const {
      code
    } = e.detail;
    let {
      videoLoadingStatus,
      panelStatus
    } = this.data;
    const {
      list
    } = this.data;
    switch (code) {
      case 2007: //启动loading
        videoLoadingStatus = 0;
        this.setData({
          playVideo: true,
          videoLoadingStatus: 0,
        })
        break;
      case 2001: //连接服务器
        videoLoadingStatus = 20 + Math.floor(Math.random() * 10 + 1);
        break;
      case 2002: //已经连接 RTMP 服务器,开始拉流
        videoLoadingStatus = 40 + Math.floor(Math.random() * 10 + 1);
        break;
      case 2008: // 解码器启动
        videoLoadingStatus = 50 + Math.floor(Math.random() * 10 + 1);
        break;
      case 2009: //视频分辨率改动
        break;
      case 2004: // 视频播放开始
        videoLoadingStatus = 80 + Math.floor(Math.random() * 10 + 1);
        break;
      case 2026: // 音频首次播放
        break;
      case 2003: //网络接收到首个视频数据包(IDR)
        videoLoadingStatus = 100;
        // let {list} = this.data;
        list[4].status = 0;
        this.setData({
          playVideo: true,
          list: [...list]
        })
        this.autoHideControl();
        // this.getDeviceCapacity();//lc
        break;
      case 2103: //网络断连, 已启动自动重连（本小程序不自动重连）
        // videoLoadingStatus = 100;
        // this.setData({
        //   showVideoControls: false,
        //   videoNetWorkError: true,
        //   videoLoadingStatus: 100,
        // })
        videoLoadingStatus = 100;
        this.setData({
          showVideoControls: false,
          videoNetWorkError: true,
          videoLoadingStatus: 100,
          loadingText: "正在重连中",
          videoHDSrc: "",
          videoSrc: "",
        })
        this.data.timer && clearTimeout(this.data.timer)
        this.data.timer = setTimeout(async () => {
          await this.handleStop3()//停止
          await this.onRetry()
        }, 500)
        this.setData({
          timer: this.data.timer
        })
        break;
      case 2033: //首次加载出来
        if (this.data.currentTab == 1 && this.data.idinfo != -1 && this.data.idinfo != -2) {
          console.log('定时器', this.data.durationSeconds);
          this.timerId = setTimeout(() => {
            this.handleStop(); //停止
            console.log('停止播放');
          }, this.data.durationSeconds + '000')
        }
        break;
      case 3001:
      case 3002:
      case 3003:
      case 3005: // 播放失败
        console.log(播放失败);
        videoLoadingStatus = 100;
        this.checkNetWork();
        this.handleStop(this.playError);
        list[5].status = -1;
        list[4].status = -1
        this.setData({
          // playVideo: false,
          showVideoControls: false,
          videoNetWorkError: true,
          videoLoadingStatus: 100,
          list: list,
        })
        break;
      case 2105: //拉流：当前视频播放出现卡顿,请自行重启播放
        videoLoadingStatus = 100;
        this.setData({
          showVideoControls: false,
          videoNetWorkError: true,
          videoLoadingStatus: 100,
          loadingText: "正在重连中",
          videoHDSrc: "",
          videoSrc: "",
        })
        this.data.timer && clearTimeout(this.data.timer)
        this.data.timer = setTimeout(async () => {
          await this.handleStop3()//停止
          await this.onRetry()
        }, 500)
        this.setData({
          timer: this.data.timer
        })
        break;
      case -2301: // 经多次重连抢救无效，更多重试请自行重启播放
        videoLoadingStatus = 100;
        list[5].status = -1;
        list[4].status = -1
        this.setData({
          // playVideo: false,
          showVideoControls: false,
          videoNetWorkError: true,
          videoLoadingStatus: 100,
          list: [...list],
        })
        break;
    }
    this.setData({
      videoLoadingStatus: videoLoadingStatus,
      playCode: code
    })
  },
  playError() {
    this.setData({
      showVideoControls: false,
      videoNetWorkError: true,
      videoLoadingStatus: 100,
    });
    this.getDeviceInfo();
    this.getDeviceCoverInfo();
  },
  error(e) {
    console.log('live-player', e);
    console.error('live-player error:', e.detail.errMsg)
    if (e.detail.errCode == 10001) {
      wx.showToast({
        title: '视频直播对讲需要你手机授权微信录音或麦克风权限',
        icon: 'none',
        duration: 3000,
      })
    }
  },
  onVideoTap2() {

  },
  onVideoTap(e) {
    console.log("点击视频");
    const {
      deviceOffline,
      showVideoControls,
      panelStatus,
      videoNetWorkError
    } = this.data;
    if (deviceOffline || panelStatus === 4 || videoNetWorkError) {
      return false;
    }
    if (showVideoControls) {
      this.setData({
        showVideoControls: false,
      });
      clearTimeout(this.data.autoHideTimer);
    } else {
      this.setData({
        showVideoControls: true,
      })
      this.autoHideControl();
    }
  },
  // tapPanel: function (event) {
  //   const {
  //     accessToken,
  //     deviceSerial,
  //     channelNo
  //   } = this.data;
  //   var tValue = event.currentTarget.dataset.value;
  //   var list = this.data.list;
  //   var panelStatus = this.data.panelStatus;
  //   switch (tValue) {
  //     case 'talk':
  //       if (list[0].status === -1) {
  //         return false;
  //       }
  //       panelStatus = 5;
  //       this.initTalk();
  //       break;
  //     case 'ptz':
  //       if (list[1].status === -1) {
  //         return false;
  //       }
  //       panelStatus = 1;
  //       break;
  //     case 'voice':
  //       if (list[2].status === -1) {
  //         return false;
  //       }
  //       panelStatus = 2;
  //       this.getDefaultVoice();
  //       this.getCustomVoice();
  //       break;
  //     case 'playback':
  //       this.goToLive();
  //       break;
  //     case 'capture':
  //       if (list[4].status === -1) {
  //         return false;
  //       }
  //       this.screenShoot()
  //       break;
  //     case 'mirror':
  //       if (list[5].status === -1) {
  //         return false;
  //       }
  //       if (panelStatus === 3) {
  //         panelStatus = 0;
  //         list[1].status = 0;
  //         list[4].status = 0;
  //         list[5].status = 0;
  //         this.sceneMirror(2);
  //       } else {
  //         panelStatus = 3;
  //         this.sceneMirror(2);
  //       }
  //       break;
  //     case 'cover':
  //       if (list[6].status === -1) {
  //         return false;
  //       }
  //       if (panelStatus === 4) { // 镜头遮蔽中
  //         this.sceneCover(0);
  //       } else {
  //         this.sceneCover(1);
  //       }
  //       break;
  //     default:
  //       panelStatus = 0;
  //   }
  //   this.setData({
  //     panelStatus: panelStatus,
  //     list: list
  //   })
  // },
  startRecord(e) {
    recorderManager.start(options)
  },
  stopRecord(e) {
    recorderManager.stop()
  },
  handleBackPanel(event) {
    var tValue = event.currentTarget.dataset.value;
    this.setData({
      panelStatus: 0,
    })
  },
  handlePtzTouchStart(event) {
    var {
      ptzStatus,
      ptzLoading,
      videoLoadingStatus,
      idinfo,
      playVideo,
      videoNetWorkError
    } = this.data;
    if (!playVideo || videoLoadingStatus != 100 || videoNetWorkError || idinfo != -1) {
      console.log("非播放状态下点击");
      return false;
    }
    wx.createSelectorQuery().select('#ptz-img-container').boundingClientRect((rect) => {
      let {
        clientX,
        clientY
      } = event.touches[0];
      let rectLeft = rect.left;
      let rectTop = rect.top;

      var centerLeft = 104 + rectLeft;
      var centerTop = 104 + rectTop;
      var left = clientX - centerLeft;
      var top = clientY - centerTop;

      console.log("点击了页面方位：pageY", clientY);
      console.log("云盘位置：top", rect.top);
      if (ptzLoading) {
        wx.showToast({
          title: '操作过于频繁，建议长按转动',
          icon: 'none'
        })
        return false;
      }
      if (Math.abs(left) > Math.abs(top)) {
        if (left > 0) {
          this.handlePtzControl(3);
          ptzStatus = 4;
        } else {
          ptzStatus = 3;
          this.handlePtzControl(2);
        }
      } else {
        if (top > 0) {
          ptzStatus = 2;
          this.handlePtzControl(1);

        } else {
          ptzStatus = 1;
          this.handlePtzControl(0);
        }
      }
      this.setData({
        ptzStatus: ptzStatus,
      })

    }).exec();
  },
  handlePtzTouchEnd(event) {
    var {
      videoNetWorkError,
      videoLoadingStatus,
      idinfo,
      playVideo
    } = this.data;
    if (!playVideo || videoLoadingStatus != 100 || videoNetWorkError || idinfo != -1) {
      console.log("非播放状态下点击");
      return false;
    }
    let {
      clientX,
      clientY
    } = event.changedTouches[0];
    const _this = this;
    wx.createSelectorQuery().select('#ptz-img-container').boundingClientRect((rect) => {
      let rectLeft = rect.left;
      let rectTop = rect.top;

      var centerLeft = 104 + rectLeft;
      var centerTop = 104 + rectTop;
      var left = clientX - centerLeft;
      var top = clientY - centerTop;
      if (Math.abs(left) > Math.abs(top)) {
        if (left > 0) {
          _this.handlePtzControl(3, 'stop');
        } else {
          _this.handlePtzControl(2, 'stop');
        }
      } else {
        if (top > 0) {
          _this.handlePtzControl(1, 'stop');
        } else {
          _this.handlePtzControl(0, 'stop');
        }
      }
    }).exec();
    this.setData({
      ptzStatus: 0,
    })
  },
  handlePtzControl(position, type) {
    const {
      accessToken,
      deviceSerial,
      channelNo,
      ptzLoading
    } = this.data;
    let ptzLimit = '';
    const ptzTopImgSuccess = './images/yuntai/top.png';
    const ptzTopImgFailed = './images/yuntai/top_limit.png';
    const ptzDownImgSuccess = './images/yuntai/down.png';
    const ptzDownImgFailed = './images/yuntai/down_limit.png';
    const ptzLeftImgSuccess = './images/yuntai/left.png';
    const ptzLeftImgFailed = './images/yuntai/left_limit.png';
    const ptzRightImgSuccess = './images/yuntai/right.png';
    const ptzRightImgFailed = './images/yuntai/right_limit.png';
    const ptzNormalImg = './images/yuntai/normal.png';
    let ptzStatus = this.data.ptzStatus;
    let currentPtzImg = this.data.currentPtzImg;
    var url = `${OPEN_DOMAIN}${PTZ_START}`;
    if (type == 'stop') {
      url = `${OPEN_DOMAIN}${PTZ_STOP}`
    }
    if (ptzLoading && type === 'start') {
      wx.showToast({
        title: '操作过于频繁，建议长按转动',
        icon: 'none'
      })
      return false;
    }

    this.setData({
      ptzLoading: true,
    })
    wx.request({
      url: url, //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        "accessToken": accessToken,
        "deviceSerial": deviceSerial,
        "channelNo": channelNo,
        "direction": position,
        speed: 1,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        const code = res.data.code;
        console.log('云台控制', res.data);
        if (code == 10029) {
          wx.showToast({
            title: '个人版接口调用超限，请升级企业版',
            icon: 'none',
          })
        } else if (code != 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }
        if (type == 'stop') {
          ptzStatus = 0;
          currentPtzImg = ptzNormalImg;
        } else {
          switch (position) {
            case 0:
              ptzStatus = 1;
              currentPtzImg = code == 200 ? ptzTopImgSuccess : ptzTopImgFailed;
              ptzLimit = code == 200 ? '' : 'top';
              break;
            case 1:
              ptzStatus = 2;
              currentPtzImg = code == 200 ? ptzDownImgSuccess : ptzDownImgFailed;
              ptzLimit = code == 200 ? '' : 'down';
              break;
            case 2:
              ptzStatus = 3;
              currentPtzImg = code == 200 ? ptzLeftImgSuccess : ptzLeftImgFailed;
              ptzLimit = code == 200 ? '' : 'left';
              break;
            case 3:
              ptzStatus = 4;
              currentPtzImg = code == 200 ? ptzRightImgSuccess : ptzRightImgFailed;
              ptzLimit = code == 200 ? '' : 'right';
              break;
            default:
              ptzStatus = 0;
              currentPtzImg = ptzTopImgSuccess;
              ptzLimit = '';
          }
        }
        this.setData({
          ptzStatus: ptzStatus,
          currentPtzImg: currentPtzImg,
          ptzLoading: false,
          ptzLimit: ptzLimit,
        });
      },
      error: (err) => {
        this.setData({
          ptzLoading: false,
        })
      }
    })
  },
  screenShoot(e) {
    const {
      playVideo,
      videoLoadingStatus,
      videoNetWorkError,
      idinfo
    } = this.data;
    if (!playVideo || videoLoadingStatus != 100 || videoNetWorkError || idinfo != -1) {
      console.log("非播放状态下点击截图");
      return false;
    }
    console.log("开始截图")
    // livePlayerContext.snapshot('raw');
    let that = this
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          that.saveImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.saveImg();
            },
            fail() {
              that.authConfirm()
            }
          })
        } else {
          that.authConfirm()
        }
      }
    })

  },
  saveImg() {
    livePlayerContext.snapshot('raw')
      .then(data => {
        console.log("data", data);
        if (data) {
          console.log(data)
          wx.saveImageToPhotosAlbum({
            filePath: data.tempImagePath,
            success(res) {
              console.log("保存成功", res)
              wx.showToast({
                title: '截图已保存至手机相册',
                icon: 'none',
              })
            }
          })
        }
      })
      .catch(err => {
        console.log("err", err);
      })
  },
  // 授权拒绝后，再次授权提示弹窗
  authConfirm() {
    let that = this
    wx.showModal({
      content: '您没打开保存图片权限，是否去设置打开？',
      confirmText: "确认",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.writePhotosAlbum']) {
                that.saveImg();
              } else {
                wx.showToast({
                  title: '您没有授权，无法保存到相册',
                  icon: 'none'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '您没有授权，无法保存到相册',
            icon: 'none'
          })
        }
      }
    });
  },
  // 镜头遮蔽
  sceneCover(enable) {
    var _this = this;
    let {
      deviceSerial,
      channelNo,
      accessToken,
      coverInterval,
      list,
      panelStatus,
      videoNetWorkError
    } = this.data;
    if (coverInterval) {
      wx.showToast({
        title: '操作过于频繁',
        icon: 'none'
      })
      return false;
    }
    this.setData({
      coverInterval: true,
    })
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/device/scene/switch/set`,
      method: 'POST',
      data: {
        accessToken: accessToken,
        deviceSerial: deviceSerial,
        channelNo: channelNo,
        enable: enable,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res.data);
        if (res.data.code == 200) {
          if (enable == 0) {
            list[6].status = 0;
            panelStatus = 0;
            videoNetWorkError = false;
            this.getDeviceCapacity();
            this.handlePlay();
          } else {
            list[0].status = -1;
            list[1].status = -1;
            list[2].status = -1;
            list[4].status = -1;
            list[5].status = -1;
            panelStatus = 4;
            list[6].status = 1;
            // this.handleStop();
            this.setData({
              playVideo: false
            })
          }
          setTimeout(() => {
            this.setData({
              coverInterval: false,
            });
          }, 5000)
          this.setData({
            videoNetWorkError: videoNetWorkError,
            list: list,
            panelStatus: panelStatus,
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
          this.setData({
            coverInterval: false,
            panelStatus: panelStatus,
          });
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        })
        this.setData({
          coverInterval: false,
        });
      }
    });
  },
  // 镜象翻转
  sceneMirror(enable) {
    const {
      deviceSerial,
      channelNo,
      accessToken,
      mirrorInterval
    } = this.data;
    var _this = this;
    if (mirrorInterval) {
      wx.showToast({
        title: '操作过于频繁',
        icon: 'none'
      })
      return false;
    }
    this.setData({
      mirrorInterval: true,
    });
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/device/ptz/mirror`, //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        accessToken: accessToken,
        deviceSerial: deviceSerial,
        channelNo: channelNo,
        command: enable,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res.data);
        if (res.data.code == 200) {
          setTimeout(() => {
            this.setData({
              mirrorInterval: false,
            });
          }, 5000)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
          this.setData({
            mirrorInterval: false,
          });
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        })
        this.setData({
          mirrorInterval: false,
        });
      }
    })
  },
  playVoice(event) {
    const {
      accessToken,
      deviceSerial,
      channelNo
    } = this.data;
    var {
      duration,
      voiceName,
      fileUrl
    } = event.currentTarget.dataset.value;
    var type = event.currentTarget.dataset.type;
    console.log("type", type)
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/voice/send`, //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        accessToken: accessToken,
        deviceSerial: deviceSerial,
        channelNo: channelNo,
        fileUrl: fileUrl,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log(res.data);
        const {
          list
        } = this.data;
        if (res.data.code == 200) {
          list[2].status = 1;
          this.setData({
            activeCustomVoiceName: type === 'custom' ? voiceName : '',
            activeDefaultVoiceName: type === 'default' ? voiceName : '',
            list: list,
          });
          setTimeout(() => {
            list[2].status = 0;
            this.setData({
              activeCustomVoiceName: '',
              activeDefaultVoiceName: '',
              list: list,
            })
          }, duration * 1000)
        } else if (res.data.code == '111012') { // 设备正忙
          wx.showToast({
            title: '语音下发失败',
            icon: 'none',
          })
        } else if (res.data.code == '20007') { // 设备正忙
          wx.showToast({
            title: '设备不在线',
            icon: 'none',
          })
        } else if (res.data.code == '20008') { // 设备正忙
          wx.showToast({
            title: '设备响应超时',
            icon: 'none',
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        })
      }
    })
  },
  speakStart(event) {
    let recoderTime = this.data.recoderTime;
    this.setData({
      recoderTime: 59,
    })
    recorderManager.start(options);
    wx.showToast({
      icon: 'none',
      duration: 60000,
      image: './images/voice_talk4.png',
      title: '剩余' + recoderTime
    });

    this.data.recoderTimer = setInterval(() => {
      // _this.setData({
      //   recoderTime: --recoderTime
      // },1000)
      if (recoderTime > 0) {
        --recoderTime;
        wx.showToast({
          icon: 'none',
          duration: 60000,
          image: './images/voice_talk4.png',
          title: '剩余' + recoderTime
        });
        this.setData({
          recoderTime: recoderTime
        })
      } else {
        clearInterval(this.data.recoderTimer);
        this.speakEnd();
      }
      // console.log("recoderTime", recoderTime)
    }, 1000)
  },
  speakEnd(event) {
    wx.hideToast();
    let recoderTime = this.data.recoderTime;
    if (recoderTime >= 59) {
      wx.showToast({
        title: '时间太短了',
        icon: 'none',
      })
      recorderManager.stop();
      clearInterval(this.data.recoderTimer);
      return false;
    } else {
      wx.hideToast();
      recorderManager.stop();
      clearInterval(this.data.recoderTimer);
    }
  },
  tapDialogButton(e) {
    this.setData({
      dialogShow: false
    });
    this.pageBack();
  },
  pageBack() {
    const {
      scene
    } = this.data;
    console.log("scene", scene);
    // wx.showToast({
    //   title: `code ${scene}`,
    // })
    if ([1007, 1008, 1036, 1037, 1038, 1044].indexOf(scene) === -1) {
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.reLaunch({
        url: '/pages/home/home',
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const {
      accessToken,
      deviceSerial,
      channelNo
    } = this.data;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
      this.setData({
        panelStatus: 0,
      })
    }
    return {
      title: '小程序',
      path: '/pages/live/live?accessToken=' + accessToken + '&deviceSerial=' + deviceSerial + '&channelNo=' + channelNo + '&scene=1007',
    }
  },
  // 通过二位码进入直播，通过uuid获取accessToken、deviceSerial、channelNo
  getWxaInfo: function () {
    const {
      pathParam
    } = this.data;
    console.log('getWxaInfo:', pathParam)
    wx.request({
      url: `${OPEN_DOMAIN}/device/getWxaInfo`, //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        uuid: pathParam
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log('通过uuid获取', res.data);
        const res1 = res.data.data;
        if (res1) {
          this.setData({
            accessToken: res1.accessToken,
            deviceSerial: res1.deviceSerial,
            channelNo: res1.channelNo
          });
          this.getPlayUrl();
          this.getDeviceInfo();
          this.getDeviceCoverInfo();
        }
      },
      fail: (res) => {
        console.log('获取accesstoken失败');
        // wx.showToast({
        //   title: '网络异常',
        //   icon: 'none'
        // })
      }
    })
  },
  // 返回回放
  goToLive() {
    const {
      accessToken,
      deviceSerial,
      channelNo
    } = this.data;
    let url = '/packageA/pages/index-inside-page/playback/playback?accessToken=' + accessToken + '&deviceSerial=' + deviceSerial + '&channelNo=' + channelNo;
    wx.navigateTo({
      url: url,
    })
  },


  /**
   * @name:   点击切换 
   */
  async swichNav(e) {
    let {
      current
    } = e.currentTarget.dataset
    console.log(current);
    console.log('   点击切换 ');
    this.setData({
      currentTab: current
    })
  },
  /**
   * @name: 滑动切换
   */
  async bindChangeTab(e) {
    let {
      current
    } = e.detail
    console.log('滑动切换');
    if (current == 0) {
      // 取消定时器  
      if (this.timerId !== null) {
        clearTimeout(this.timerId);
        console.log('定时器已手动停止');
        this.timerId = null; // 可选：将timerId重置为null，以表明没有活动的定时器  
      }
      if (this.data.idinfo != -1) {
        this.setData({
          idinfo: -1,
          loadingText: "视频安全传输中",
        })
        await this.handleStop(); //停止
        await this.getPlayUrl(); //直播
      }
    } else if (current == 1) {
      if (this.data.dateLine.length == 0) {
        if (JSON.stringify(this.data.date) == JSON.stringify(this.data.dateTime)) {
          console.log('当天时间');
          // 日期是当天时间
          let currentTimeMillis = new Date().getTime(); //当前时间毫秒数
          let sixHoursAgoMillis = currentTimeMillis - (4 * 3600000); // 计算当前时间前4个小时的时间毫秒数  
          this.setData({
            endTimeet: currentTimeMillis,
            startTimest: sixHoursAgoMillis,
            IsNextPage: false,
            Arr: [],
            dateLine: [],
          })
        } else {
          console.log('当天时间之外');
          var dateParts = this.data.dateTime.split("-"); // 使用split方法分割字符串  
          var month = parseInt(dateParts[1], 10) - 1; // 将月份从字符串转换为数字，并减去1  
          var newDateString = dateParts[0] + "," + month + "," + dateParts[2]; // 重新组合字符串，月份部分使用新的值 
          console.log(newDateString);
          // 录像分页逻辑
          // let dateObj = new Date(JSON.stringify(this.data.dateTime));//此方法不兼容苹果机，谨慎使用--lc
          let dateObj = new Date(dateParts[0], month, dateParts[2]);
          dateObj.setHours(23, 59, 59, 0); // 将时间设置为当天的23:59:59  
          let endTimeMillis = dateObj.getTime(); // 将时间设置为当天的23:59:59  
          // console.log(endTimeMillis);
          let sixHoursAgoMillis = endTimeMillis - (4 * 3600000); // 计算当前时间前4个小时的时间毫秒数
          this.setData({
            endTimeet: endTimeMillis, // 将时间设置为当天的23:59:59  
            startTimest: sixHoursAgoMillis,
            IsNextPage: false,
            Arr: [],
            dateLine: [],
          })
        }
        this.getTimeLine()
      }
    } else if (current == 2) {

    }
    this.setData({
      currentTab: current
    })
  },
  format: function (now) {
    var time = new Date(now);
    var h = time.getHours(); //返回日期中的小时数（0到23）
    var m = time.getMinutes(); //返回日期中的分钟数（0到59）
    var s = time.getSeconds(); //返回日期中的秒数（0到59）
    return (h > 9 ? h : '0' + h) + ':' + (m > 9 ? m : '0' + m) + ':' + (s > 9 ? s : '0' + s);
  },
  // 计算时间差
  calculateDuration(startTime, endTime) {
    // 将时间字符串分割为时、分、秒  
    const [startH, startM, startS] = startTime.split(':').map(Number);
    const [endH, endM, endS] = endTime.split(':').map(Number);
    // 计算秒数差  
    const totalSecondsStart = startH * 3600 + startM * 60 + startS;
    const totalSecondsEnd = endH * 3600 + endM * 60 + endS;
    // 计算差值  
    const diffInSeconds = totalSecondsEnd - totalSecondsStart;
    // 将秒数差转换为小时、分钟和秒  
    let hours = Math.floor(diffInSeconds / 3600);
    let minutes = Math.floor((diffInSeconds % 3600) / 60);
    let seconds = diffInSeconds % 60;
    // 确保每个单位都是两位数  
    hours = hours.toString().padStart(2, '0');
    // minutes = minutes.toString().padStart(2, '0');  
    seconds = seconds.toString().padStart(2, '0');
    // 返回格式化的时间差  
    return `${minutes}'${seconds}'`;
  },
  // 将时间字符串转换为秒数  
  timeStrToSeconds(timeStr) {
    let [hours, minutes, seconds] = timeStr.split(':').map(Number);
    return hours * 3600 + minutes * 60 + seconds;
  },
  // 时间选择器
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    });
    this.getTimeLine();
  },
  // 获取播放片段
  getTimeLine: function () {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0,
      // mask:true
    });
    // this.setData({
    //   flag:true
    // })
    const {
      recType,
      accessToken,
      deviceSerial,
      channelNo,
      dateTime
    } = this.data;
    console.log('获取到的accessToken, accessToken', accessToken);
    let timestampCurrent = null;
    let timestampToday = null;
    // 时间戳转换：Date.parse(new Date("2020-09-23 12:13:56"))
    if (dateTime) {
      let currentTimeMillis = new Date().getTime();
      const time = dateTime + ' ' + '00:00:00';
      const endTime = dateTime + ' ' + '23:59:59'
      timestampToday = Date.parse(new Date(time.replace(/\-/g, '/'))); // 选择日期凌晨时间戳
      timestampCurrent = Date.parse(new Date(endTime.replace(/\-/g, '/'))); // 选择日期时间戳
    }
    this.setData({
      nottext: "暂无录像",
    });
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/video/by/time`,
      method: 'POST',
      data: {
        accessToken: accessToken,
        deviceSerial: deviceSerial,
        channelNo: channelNo,
        recType: recType,
        // startTime: timestampToday,
        // endTime: timestampCurrent,
        startTime: this.data.startTimest,
        endTime: this.data.endTimeet,
        version: '2.0',
        pageSize: 500
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log('获取播放时间片段', res);
        if (res.data.code == 200) {
          if (res.data.data.files.length != 0) {
            var result = res.data.data.files;
            const len = result.length;
            let availArr = [];
            for (let i = len - 1; i >= 0; i--) {
              let res = result[i];
              let et = null;
              let st = null;
              let duration = null; //分钟+秒
              let durationSeconds = null; //秒
              let timeData = null; //时间段
              // 最近片段可能存在endTime超过当前时间
              if (i == (len - 1) && (res.endTime > timestampCurrent)) {
                et = this.format(timestampCurrent)
              } else {
                et = this.format(res.endTime)
              }
              // 存在startTime可能为前一天的时间
              if (i == 0 && (res.startTime < timestampToday)) {
                st = this.format(timestampToday)
              } else {
                st = this.format(res.startTime);
              }
              duration = this.calculateDuration(st, et);
              durationSeconds = this.timeStrToSeconds(et) - this.timeStrToSeconds(st);
              timeData = st.slice(0, 2);
              availArr.push({
                st: st,
                et: et,
                duration: duration,
                durationSeconds: durationSeconds,
                timeData: timeData,
                id: i
              })
            }
            if (this.data.Arr.length == 0) {
              this.setData({
                Arr: availArr,
              })
            } else {
              this.setData({
                Arr: this.data.Arr.concat(availArr),
              })
            }
            console.log('availArr:', availArr);
            let arr = this.data.Arr.sort(function (a, b) {
              return parseInt(JSON.stringify(b.st), 10) - parseInt(JSON.stringify(a.st), 10);
            });
            // 使用reduce来按time字段分组  
            const groupedByTime = arr.reduce((acc, item) => {
              // 检查acc中是否已存在对应的time分组  
              const existingGroup = acc.find(group => group.timeData === item.timeData);
              if (existingGroup) {
                // 如果存在，则将该item添加到对应的cList中  
                existingGroup.dateArr.push(item);
              } else {
                // 如果不存在，则创建一个新的分组  
                acc.push({
                  timeData: item.timeData,
                  dateArr: [item]
                });
              }
              return acc;
            }, []); // 初始累加器为一个空数组  
            console.log(groupedByTime);
            this.setData({
              dateLine: groupedByTime,
            })
          } else {
            console.log("暂无录像");
            this.setData({
              // dateLine: [],
              nottext: "暂无录像",
            });
            // showMsg('暂无录像');
            // this.handleStop();
          }
        } else if (res.data.code == '10002') {
          this.setData({
            // dialogTitle: '',
            // dialogContent: 'accessToken过期或异常',
            // dialogShow: true,
            // dateLine: [],
            nottext: "暂无录像",
          })
          showMsg('暂无录像')
          // Dialog.alert({
          //   message: 'accessToken过期或异常',
          // }).then(() => {
          // });
        } else if (res.data.code == "20002") {
          this.setData({
            // dateLine: [],
            nottext: "设备不存在",
          })
          // 设备不存在
          showMsg('设备不存在')
        } else if (res.data.code == "20007") {
          this.setData({
            // dateLine: [],
            nottext: "设备不在线",
          })
          showMsg('设备不在线')
        } else if (res.data.code == "20008") {
          this.setData({
            // dateLine: [],
            nottext: "设备响应超时，请重试",
          });
          showMsg('设备响应超时，请重试')
        } else {
          this.setData({
            // dateLine: [],
            nottext: res.data.msg,
          })
          showMsg(res.data.msg)
          // Dialog.alert({
          //   message: res.data.msg,
          // }).then(() => {});
        }
        Toast.clear();
        // this.setData({
        //   flag:false
        // })
      }
    })
  },
  // 滚动到底部触发
  alarmLower() {
    console.log(111);
    if (this.data.IsNextPage) return;
    let endTimeet = this.data.startTimest; //当前时间毫秒数
    let sixHoursAgoMillis = this.data.startTimest - (4 * 3600000); // 计算当前时间前6个小时的时间毫秒数  
    console.log(sixHoursAgoMillis, ' 计算当前时间前6个小时的时间毫秒数  ');
    // 创建一个表示sixHoursAgoMillis的Date对象  
    let sixHoursAgoDate = new Date(sixHoursAgoMillis);

    // let todayStart = new Date();
    // todayStart.setHours(0, 0, 0, 0); // 当前时间00点  
    var dateParts = this.data.dateTime.split("-"); // 使用split方法分割字符串  
    var month = parseInt(dateParts[1], 10) - 1; // 将月份从字符串转换为数字，并减去1  
    var newDateString = dateParts[0] + "," + month + "," + dateParts[2]; // 重新组合字符串，月份部分使用新的值 
    console.log(newDateString);
    // let todayStart = new Date(JSON.stringify(this.data.dateTime));//此方法不兼容苹果机，谨慎使用--lc
    let todayStart = new Date(dateParts[0], month, dateParts[2]);
    todayStart.setHours(0, 0, 0, 0); // 当前时间00点  
    // 检查是否超过了当天的00点  
    if (sixHoursAgoDate < todayStart) {
      // 如果sixHoursAgoDate小于当天的00点，说明已经跨天了  
      sixHoursAgoMillis = todayStart.getTime(); // 将sixHoursAgoMillis设置为当天的00点时间毫秒数  
      console.log(sixHoursAgoMillis, ' 计算当前时间前6个小时的时间毫秒数  处理过 ');
      this.setData({
        IsNextPage: true
      })
    }
    // if (!this.data.alarmIsNextPage) return
    this.setData({
      endTimeet: endTimeet,
      startTimest: sixHoursAgoMillis,
    })
    this.getTimeLine()
  },
  // 停止
  handleStop2(callback) {
    console.log("stop");
    livePlayerContext.stop({
      success: () => {
        this.setData({
          videoLoadingStatus: 10,
          videoNetWorkError: false
        })
        if (callback && typeof callback === "function") {
          callback();
        }
      },
      fail: (error) => {
        console.log("停止播放失败")
      }
    })
  },
  // 点击录像片段
  onPlay(e) {
    console.log(e);
    console.log(e.currentTarget.dataset.item.st);
    // 先停止
    this.handleStop2();
    this.setData({
      durationSeconds: e.currentTarget.dataset.item.durationSeconds,
      // idinfo: e.currentTarget.dataset.item.id,
      idinfo: e.currentTarget.dataset.item.st,
      loadingText: "视频安全传输中",
      isHD: false,
    })
    const {
      date,
      accessToken,
      deviceSerial,
      channelNo,
      videoSrc,
      dateTime,
    } = this.data;
    console.log(dateTime);
    const param = {
      'accessToken': accessToken,
      'channelNo': channelNo,
      'deviceSerial': deviceSerial,
      'protocol': 3, // 流播放协议，1-ezopen、2-hls、3-rtmp
      'startTime': dateTime + ' ' + e.currentTarget.dataset.item.st,
      'stopTime': dateTime + ' ' + e.currentTarget.dataset.item.et,
      'type': 2,
      'expireTime': 86400,
      "supportH265": "1",
      "quality": 2
    }
    // 获取回放播放地址
    this.getPlayUrl2(param);
  },
  // 获取回放播放地址
  getPlayUrl2(param) {
    wx.request({
      url: `${OPEN_DOMAIN}/api/lapp/v2/live/address/get`,
      method: 'POST',
      data: param,
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log('获取到的回放播放地址：', res.data);
        if (res.data.code == "200" && res.data.data && res.data.data.url) {
          const playUrl = res.data.data.url;
          this.setData({
            videoSrc: playUrl,
            playFlag: true,
          });
          // 开始播放
          setTimeout(() => {
            this.handlePlay();
          }, 500)
          console.log('当前播放地址：', this.data.videoSrc);
        } else if (res.data.code == "20007") {
          //   debugger;
          Dialog.alert({
            message: '设备不在线',
          }).then(() => {});
        } else if (res.data.code == "20002") {
          Dialog.alert({
            message: '设备不存在',
          }).then(() => {});
        } else if (res.data.code == "20001") {
          Dialog.alert({
            message: '摄像头不存在',
          }).then(() => {});
        } else if (res.data.code == "20018") {
          Dialog.alert({
            message: '用户不拥有该设备',
          }).then(() => {});
        } else if (res.data.code == "10001") {
          Dialog.alert({
            message: '参数错误',
          }).then(() => {});
        } else if (res.data.code == "60019") {
          Dialog.alert({
            message: '设备已被加密，无法继续查看，请前往萤石云app解密。',
          }).then(() => {});
        } else {
          Dialog.alert({
            message: res.data.msg,
          }).then(() => {});
          console.log("获取rtmp播放地址失败")
        }
      }
    })
  },
  // 前一天
  onPreDay() {
    if (!this.data.isDay) return
    if (this.data.defaultDate - 86400000 < this.data.minDate) {
      this.setData({
        isDay: false,
      })
    }
    this.setData({
      defaultDate: this.data.defaultDate - 86400000,
      dateTime: this.formatDate(new Date(this.data.defaultDate - 86400000)),
      isClick: true,
      dateLine: [],
    })
    var dateParts = this.data.dateTime.split("-"); // 使用split方法分割字符串  
    var month = parseInt(dateParts[1], 10) - 1; // 将月份从字符串转换为数字，并减去1  
    var newDateString = dateParts[0] + "," + month + "," + dateParts[2]; // 重新组合字符串，月份部分使用新的值 
    console.log(newDateString);
    // 录像分页逻辑
    let dateObj = new Date(dateParts[0], month, dateParts[2]);
    dateObj.setHours(23, 59, 59, 0); // 将时间设置为当天的23:59:59  
    let endTimeMillis = dateObj.getTime(); // 将时间设置为当天的23:59:59  
    let sixHoursAgoMillis = endTimeMillis - (4 * 3600000); // 计算当前时间前4个小时的时间毫秒数
    this.setData({
      endTimeet: endTimeMillis, // 将时间设置为当天的23:59:59  
      startTimest: sixHoursAgoMillis,
      IsNextPage: false,
      Arr: [],
    })
    this.getTimeLine();
  },
  // 后一天
  onNextDay() {
    if (!this.data.isClick) return
    if (this.data.defaultDate + 86400000 >= new Date(dataHandle()).getTime()) {
      this.setData({
        isClick: false,
      })
    }
    this.setData({
      defaultDate: this.data.defaultDate + 86400000,
      dateTime: this.formatDate(new Date(this.data.defaultDate + 86400000)),
      isDay: true,
      dateLine: [],
    })

    if (JSON.stringify(this.data.date) == JSON.stringify(this.data.dateTime)) {
      console.log('当天时间');
      // 日期是当天时间
      let currentTimeMillis = new Date().getTime(); //当前时间毫秒数
      let sixHoursAgoMillis = currentTimeMillis - (4 * 3600000); // 计算当前时间前4个小时的时间毫秒数  
      this.setData({
        endTimeet: currentTimeMillis,
        startTimest: sixHoursAgoMillis,
        IsNextPage: false,
        Arr: [],
      })
    } else {
      console.log('当天时间之外');
      console.log(this.data.dateTime);
      var dateParts = this.data.dateTime.split("-"); // 使用split方法分割字符串  
      var month = parseInt(dateParts[1], 10) - 1; // 将月份从字符串转换为数字，并减去1  
      var newDateString = dateParts[0] + "," + month + "," + dateParts[2]; // 重新组合字符串，月份部分使用新的值 
      console.log(newDateString);
      // 录像分页逻辑
      let dateObj = new Date(dateParts[0], month, dateParts[2]);
      dateObj.setHours(23, 59, 59, 0); // 将时间设置为当天的23:59:59  
      let endTimeMillis = dateObj.getTime(); // 将时间设置为当天的23:59:59  
      let sixHoursAgoMillis = endTimeMillis - (4 * 3600000); // 计算当前时间前4个小时的时间毫秒数
      this.setData({
        endTimeet: endTimeMillis, // 将时间设置为当天的23:59:59  
        startTimest: sixHoursAgoMillis, // 计算当前时间前4个小时的时间毫秒数
        IsNextPage: false,
        Arr: [],
      })
    }
    this.getTimeLine();
  },
  onCalendar() {
    this.setData({
      isShowCalendar: !this.data.isShowCalendar
    })
  },
  onCalendarClose() {
    this.setData({
      isShowCalendar: false
    });
  },
  // 日历相关操作
  onCalendarConfirm(date) {
    if (JSON.stringify(this.data.date) == JSON.stringify(this.formatDate(date.detail))) {
      console.log('当天时间');
      // 日期是当天时间
      let currentTimeMillis = new Date().getTime(); //当前时间毫秒数
      let sixHoursAgoMillis = currentTimeMillis - (4 * 3600000); // 计算当前时间前4个小时的时间毫秒数  
      this.setData({
        endTimeet: currentTimeMillis,
        startTimest: sixHoursAgoMillis,
        IsNextPage: false,
        Arr: [],
        dateLine: [],
      })
    } else {
      console.log('当天时间之外');
      // 录像分页逻辑
      let dateObj = new Date(date.detail);
      dateObj.setHours(23, 59, 59, 0); // 将时间设置为当天的23:59:59  
      let endTimeMillis = dateObj.getTime(); // 将时间设置为当天的23:59:59  
      let sixHoursAgoMillis = endTimeMillis - (4 * 3600000); // 计算当前时间前4个小时的时间毫秒数
      this.setData({
        endTimeet: endTimeMillis, // 将时间设置为当天的23:59:59  
        startTimest: sixHoursAgoMillis,
        IsNextPage: false,
        Arr: [],
        dateLine: [],
      })
    }

    this.onCalendarClose()
    this.setData({
      dateTime: this.formatDate(date.detail),
      defaultDate: new Date(date.detail).getTime(),
      isClick: new Date(date.detail).getTime() == new Date(dataHandle()).getTime() ? false : true,
      isDay: this.data.minDate > new Date(date.detail).getTime() ? false : true,
    })
    this.getTimeLine();
  },
  formatDate(date) {
    return `${date.getFullYear()}-${JSON.stringify(date.getMonth() + 1).length > 1 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)}-${JSON.stringify(date.getDate()).length > 1 ? date.getDate() : '0' + date.getDate()}`;
  },
  onTime() {
    this.setData({
      cardType: 1
    })
  },
  onCard() {
    this.setData({
      cardType: 2
    })
  },
  // 获取播放时间片段
  getPalyParam: function (e) {
    this.setData({
      idinfo: -2,
      isHD: false,
      loadingText: "视频安全传输中",
    })
    console.log('获取播放时间片段', e);
    let stTime = e.detail.stTime;
    let etTime = e.detail.etTime;
    const {
      type,
      date,
      dateTime,
      accessToken,
      deviceSerial,
      channelNo,
      videoSrc,
    } = this.data;
    console.log('当前播放时间', stTime, etTime);

    let startTime = null;
    let stopTime = null;

    startTime = dateTime + ' ' + stTime;
    // stopTime = dateTime + ' ' + etTime;//lc
    stopTime = dateTime + ' ' + '23:59:59'; //lc
    console.log(startTime, stopTime);
    const param = {
      'accessToken': accessToken,
      'channelNo': channelNo,
      'deviceSerial': deviceSerial,
      'protocol': 3, // 流播放协议，1-ezopen、2-hls、3-rtmp
      'startTime': startTime,
      'stopTime': stopTime,
      'type': 2,
      'expireTime': 86400,
      "supportH265": "1",
      "quality": "2"
    }
    // 获取回放播放地址
    this.getPlayUrl2(param);
  },
  // 停止云台控制
  bindtouchendFn() {
    var {
      videoNetWorkError,
      videoLoadingStatus,
      idinfo,
      playVideo,
      ptzLoading
    } = this.data;
    if (!playVideo || videoLoadingStatus != 100 || videoNetWorkError || idinfo != -1) {
      console.log("非播放状态下点击");
      return false;
    }
    // if (ptzLoading) {
    //   wx.showToast({
    //     title: '操作过于频繁，建议长按转动',
    //     icon: 'none'
    //   })
    //   return false;
    // }

    this.setData({
      ptzLoading: true,
    })
    wx.request({
      url: `https://open.ys7.com/api/lapp/device/ptz/stop`,
      method: 'POST',
      data: {
        accessToken: this.data.accessToken,
        deviceSerial: this.data.deviceSerial,
        channelNo: 1,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {
        console.log('停止云台');
        this.setData({
          cloud: '4',
          ptzLoading: false,
        })
      }
    });
  },
  // 云台控制
  cloudControl(e) {
    var {
      videoNetWorkError,
      videoLoadingStatus,
      idinfo,
      playVideo,
      ptzLoading
    } = this.data;
    if (!playVideo || videoLoadingStatus != 100 || videoNetWorkError || idinfo != -1) {
      console.log("非播放状态下点击");
      return false;
    }
    // if (ptzLoading) {
    //   wx.showToast({
    //     title: '操作过于频繁，建议长按转动',
    //     icon: 'none'
    //   })
    //   return false;
    // }
    console.log(e.currentTarget.dataset.index);
    let direction
    if (e.currentTarget.dataset.index == 'top') {
      direction = 0
    } else if (e.currentTarget.dataset.index == 'right') {
      direction = 3
    } else if (e.currentTarget.dataset.index == 'bottom') {
      direction = 1
    } else if (e.currentTarget.dataset.index == 'left') {
      direction = 2
    }
    if (this.data.PageActive) {
      this.data.PageActive = false;
      wx.request({
        url: `https://open.ys7.com/api/lapp/device/ptz/start`,
        method: 'POST',
        data: {
          accessToken: this.data.accessToken,
          deviceSerial: this.data.deviceSerial,
          channelNo: 1,
          direction: direction,
          speed: 1,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: (res) => {
          console.log('开始转动');
          this.setData({
            cloud: direction
          })
        }
      });
      setTimeout(() => {
        this.data.PageActive = true;
      }, 1500);
    } else {
      console.log('操作过于频繁，建议长按转动');
      showMsg('操作过于频繁，建议长按转动');
      return;
    }
  },
  onPan() {

  },

})